clc;clear;clearvars;
% 随机生成5个数据
num_initial = 5;
num_vari = 5;
% 搜索区间
upper_bound = 5.12;
lower_bound = -5.12;
iter = 1000;
w = 1;
% 随机生成5个数据,并获得其评估值
sample_x = lhsdesign(num_initial, num_vari).*(upper_bound - lower_bound) + lower_bound.*ones(num_initial, num_vari);
sample_y = F1(sample_x);
Fmin = zeros(iter, 1);
k = 1;

% 初始化一些参数
pbestx = sample_x;
pbesty = sample_y;
% 当前位置信息presentx
presentx = lhsdesign(num_initial, num_vari).*(upper_bound - lower_bound) + lower_bound.*ones(num_initial, num_vari);
vx = sample_x;
[fmin, gbest] = min(pbesty);
for i = 1 : iter
    r = rand(num_initial, num_vari);
    % pso更新下一步的位置,这里可以设置一下超过搜索范围的就设置为边界
    vx = w.*vx + 2 * r .* (pbestx - presentx) + 2 * r .* (pbestx(gbest, :) - presentx);
    vx(vx > upper_bound) = upper_bound;
    vx(vx < lower_bound) = lower_bound;
    presentx = presentx + vx;
    presentx(presentx > upper_bound) = upper_bound;
    presentx(presentx < lower_bound) = lower_bound;
    presenty = F1(presentx);
    % 更新每个单独个体最佳位置
    pbestx(presenty < pbesty, :) = presentx(presenty < pbesty, :);
    pbesty = F1(pbestx);
    % 更新所有个体最佳位置
    [fmin, gbest] = min(pbesty);
    fprintf("iter %d fmin: %.4f\n", i, fmin);
    Fmin(k, 1) = fmin;
    k = k +1;
    % w = w - 0.0002;
end
plot(Fmin);